﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using HZYProject.Service;
using HZYProject.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HZYProject.Web.Controllers
{
    [Route("user")]
    [Authorize]
    public class UserController : Controller
    {
        private readonly IRepository<User, Guid> _userRepository;
        private readonly IUserService _userService;
        private readonly IRepository<Role, Guid> _roleRepository;

        public UserController(IRepository<User, Guid> userRepository, IUserService userService, IRepository<Role, Guid> roleRepository)
        {
            _userRepository = userRepository;
            _userService = userService;
            _roleRepository = roleRepository;
        }

        [HttpGet("")]
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost("")]
        public async Task<IActionResult> Index(UserQueryModel model)
        {
            GetUserInput userInput = new GetUserInput { CurrentPage = model.Page, MaxResultCount = model.Limit, RealName = model.RealName, UserName = model.UserName };
            var data = await _userService.GetPaginatedResult(userInput);
            return Json(new { code = 0, msg = "", data = data.Data, count = data.TotalCount });
        }

        [HttpGet("add")]
        public IActionResult Insert()
        {
            return View();
        }

        [HttpPost("remove/{id}")]
        public IActionResult Remove(Guid id)
        {
            var u = new User { UserId = id };
            _userRepository.Delete(u);
            return Json(new { success = 1, msg = "删除成功" });
        }

        [HttpGet("frole/{id}")]
        public IActionResult FenPeiRole(Guid id)
        {
            var u = _userService.GetUser(id);
            var roles = _roleRepository.GetAllList();
            UserModel um = new UserModel { User = u, Roles = roles };
            return View(um);
        }
        [HttpPost("frole")]
        public IActionResult FenPeiRole(Guid userId,Guid[] roles)
        {
            _userService.FenPeiRole(userId, roles);
            return Json(new { success = 1, msg = "分配成功" });
            
        }
    }
}
